package cn.wolfcode.producer._02_send_type;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

public class Producer {

    public static void main(String[] args) throws Exception {
        //1 创建消息的发送者
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("producer-demo");
        //2 设置名字服务
        defaultMQProducer.setNamesrvAddr("127.0.0.1:9876");
        //3 启动生产者
        defaultMQProducer.start();
        CountDownLatch countDownLatch = new CountDownLatch(50);
        //4 创建消息
        //4.1 创建消息对象(指定主题以及发送的内容[数组的形式])
        Message message = new Message("02-send-type", "Hello RocketMQ".getBytes());
        for (int i = 0; i < 50; i++) {
        //4.2 发送消息
            defaultMQProducer.send(message, new SendCallback() {

                //发送成功的话什么
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息发送成功");
                    countDownLatch.countDown();
                }

                //发送失败的话什么
                @Override
                public void onException(Throwable throwable) {
                    System.out.println("消息发送失败");
                    countDownLatch.countDown();
                }
            });
        }
//        System.out.println(sendResult.getSendStatus());//查看发送的状态
//        System.out.println(sendResult.getMsgId());//查看消息的id
        countDownLatch.wait();
        //5 关闭连接
        defaultMQProducer.shutdown();
    }
}
